True even today

Mr. Muskrat on 2004-01-30T06:29:47

(Especially in IT)

"A little inaccuracy sometimes saves a ton of explanation."
      - H. H. Munro (Saki) (1870-1916)


So true!

merlyn on 2004-01-30T12:46:15

I start the Llama Course by saying "we're gonna lie a little bit, rounding off the corners". Of course, I have to be careful about what I lie about, but do you really want to tell a beginner that chomp depends on a magic $/ variable when all you're trying to do is get rid of that darn newline on a line you've just read?

Education is an iterative and recursive process.

chomp magic

Mr. Muskrat on 2004-01-30T17:22:34

Thank you for the reminder about chomp using the value of $/.

I sent out an email to our development group as a refresher:

We all know and use chomp, right?

It's the function that we use to remove trailing newlines. But did you know that it works on more than just scalars? Used on an array, it will chomp each element. Used on a hash, it will chomp the values but not the keys. It returns the total number of characters removed.

The coolest part of this function is that you can set $/ to whatever you like! If you set $/ = "" (paragraph mode), chomp will remove all trailing newlines. If you set $/ = undef (slurp mode) or to a reference to an integer (fixed-length record mode), chomp will remove nothing.

Example 1:
#!/usr/bin/perl
$_ = "foo bar baz\nflarg\n";
$/ = "flarg\n";
chomp;
print;

Example 2:
--- files.list ---
foo.txt
bar.txt
baz.txt
flarg.txt

[mmusgrove@dev working]$ perl -lpe 'BEGIN{ $/ = ".txt\n"; }' files.list